package com.lnb.controller;

import java.util.ArrayList;


import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lnb.entity.Modules;
import com.lnb.entity.RoleModules;
import com.lnb.entity.Roles;
import com.lnb.mapper.ModulesMapper;
import com.lnb.service.IModulesService;
import com.lnb.service.IRoleModulesService;
import com.lnb.util.Result;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author liningbo
 * @since 2020-05-21
 */
@RestController
@RequestMapping("/modules")
public class ModulesController {

	@Autowired
	IModulesService service;
	
	@Autowired
	IRoleModulesService iRoleModulesService;

	@PostMapping("/insert")
	public Object insert(@Valid Modules entity) {
		boolean res = service.save(entity);
		if (res) {
			return new Result(0, "添加成功");
		} else {
			return new Result(1, "添加失败");
		}
	}

	@PostMapping("/update")
	public Object update(@Valid Modules entity, @RequestParam Integer id) {
		entity.setId(id);
		boolean res = service.updateById(entity);
		if (res) {
			return new Result(0, "修改成功");
		} else {
			return new Result(1, "修改失败");
		}
	}

	@GetMapping("/delete")
	public Object delete(@RequestParam Integer rid) {
		boolean res = service.removeById(rid);
		if (res) {
			return new Result(0, "删除成功");
		} else {
			return new Result(1, "删除失败");
		}

	}

	/**
	 * 所有模块(树形)
	 * @param rid
	 * @return
	 */
	@GetMapping("/getModulesTree")
	public Object getModulesTree() {
		List<Modules> list = service.getModulesTree();
		return list;
	}
	/**
	 * 所有模块(树形)-----勾选指定角色拥有的模块
	 * @param rid
	 * @return
	 */
	@GetMapping("/getModulesTreeByRoleId")
	public Object getModulesTreeByRoleId(Integer rid) {
		List<Modules> list = service.getModulesTreeByRoleId( rid );
		return list;
	}
	
	/**
	 * 给角色设置拥有的模块
	 * @param rid
	 * @return mids 选中的模块id组成的字符串
	 */
	@PostMapping("/setModulesByRoleId")
	public Object setModulesByRoleId(@RequestParam Integer rid,@RequestParam String mids) {
		//1.删除指定角色的 所属模块（中间表）
		QueryWrapper<RoleModules> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("role_id", rid);
		iRoleModulesService.remove(queryWrapper);
		
		//2.批量添加（中间表）
		List<RoleModules> list = new ArrayList<>();
		
		String[] arr = mids.split(",");
		for(String s:arr) {
			list.add(new RoleModules(0,rid,Integer.valueOf(s)));
		}
		
		boolean res = iRoleModulesService.saveBatch(list);
		if(res) {
			return new Result(0,"设置成功");
		}else {
			return new Result(1,"设置失败");
		}
	}
}
